/**
 * Created by admin on 2016/11/24.
 */
var co = require('co');
var Promise = require("bluebird");
var assert = require('./../routes/assert');
var mongoose = require('mongoose');
mongoose.connect('mongodb://120.26.134.103:4000/parse');

var Schema = mongoose.Schema;
// 定义模型
var Store = mongoose.model('OPStore', new Schema({_id: String}), 'OPStore');
var TradeLog = mongoose.model('KDTradeLog', new Schema({_id: String, tourist: Number, userCount: Number, turnover: Number, orderCount:Number, income:Number, _p_store:String, _updated_at:Date, _created_at:Date, type: String},{versionKey: false}), 'KDTradeLog');
var Order = mongoose.model('OPOrder', new Schema({_created_at: Date, _id: String, orderProducts:Array, status: Number, _updated_at:Date, checkArrived:String}), 'OPOrder');

// 生成随机的parseId
function stringGen(len)
{
    var text = " ";
    var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIZKLMNOPQRSTUVWXYZ0123456789";
    for( var i=0; i < len; i++ )
        text += charset.charAt(Math.floor(Math.random() * charset.length));
    return text;
}

function calculate_trade() {
    co(function* () {
        try {
            // 获取所有的店铺
            var stores = yield new Promise(function (resolve, reject) {
                var query = Store.find().select({ _id: 1});
                var promise = query.exec();
                promise.then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            console.log(error);
        }
        try {
            var today = new Date();
            var yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);
            console.log(today, yesterday);
            // 获取过去一天的所有订单
            var orders = yield new Promise(function (resolve, reject) {
                var query = Order.find({_created_at:{$gt: yesterday, $lt: today}}).select({payPrice:1, _p_store:1, _p_user:1, cost:1});
                var promise = query.exec();
                promise.then(function (res) {
                    resolve(res);
                }, function (error) {
                    reject(error)
                });
            });
        }catch (error){
            console.log(error);
        }
        var store_list = [];
        var store_info = {};
        // 为每一个店铺创建一个店铺info
        stores.forEach(function (item) {
            var store = 'OPStore$'+item._id;
            store_info[store] = {'turnover':0, 'orderCount':0, 'income':0, 'tourist': 0, 'userCount': 0};
            store_list.push(store);
        });


        // 遍历说有订单，计算店铺的info
        orders.forEach(function (item) {
            var store = item.get('_p_store');
            store_info[store]['turnover'] += item.get('payPrice');
            store_info[store]['orderCount'] += 1;
            store_info[store]['income'] += item.get('payPrice') - item.get('cost');
        });
        // 将店铺的info插入到数据库
        for (var item in store_info){
            store_info[item]['_p_store'] = item;
            store_info[item]['_id'] = stringGen(11);
            store_info[item]['type'] = 'week';
            store_info[item]['_updated_at'] = new Date();
            store_info[item]['_created_at'] = new Date();
            var tradeLog = new TradeLog(store_info[item]);
            tradeLog.save().then(function (res) {
                if (res){
                    console.log('save success');
                }
            }, function (error) {
                console.log(error);
            });
        }
    });
}
function getPV(stores) {
    var client = assert.getRedis();
    stores.forEach(function (item) {
        client.get(item.id, function (err, reply) {
            var tourist = 0;
            if (typeof reply == 'string'){
                tourist = parseInt(reply);
                console.log(tourist);
            }
        });
    });
}
calculate_trade();
function check_monthIsExist(){

}
// getPV();